﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;
using System.Reflection;

public static class GoogleExtensions
{
    public static HtmlString GoogleMap(this HtmlHelper htmlHelper, IDictionary<string, object> mapValues, IDictionary<string, object> attributes)
    {
        var builder = new TagBuilder("img");
        var source = new StringBuilder();
        var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
        const string template = "{0}={1}&";

        source.Append("http://maps.google.com/maps/api/staticmap?");

        // Create the Url
        foreach (var key in mapValues.Keys)
            source.AppendFormat(template, key, urlHelper.Encode(mapValues[key].ToString()));

        // remove the last ampersand
        var finalSource = source.ToString().Remove(source.Length - 1, 1);

        builder.Attributes["src"] = finalSource;
        builder.MergeAttributes(attributes);

        return new HtmlString(builder.ToString(TagRenderMode.SelfClosing));
    }

    public static HtmlString GoogleMap(this HtmlHelper htmlHelper, object values)
    {
        return GoogleMap(htmlHelper, values, null);
    }

    public static HtmlString GoogleMap(this HtmlHelper htmlHelper, object values, object attributes)
    {
        return GoogleMap(htmlHelper, values.TurnObjectIntoDictionary(), attributes.TurnObjectIntoDictionary());
    }

    public static IDictionary<string, object> TurnObjectIntoDictionary(this object data)
    {
        var attr = BindingFlags.Public | BindingFlags.Instance;
        var dict = new Dictionary<string, object>();

        if (data == null)
            return dict;

        foreach (var property in data.GetType().GetProperties(attr).Where(property => property.CanRead))
            dict.Add(property.Name, property.GetValue(data, null));

        return dict;
    }
}
